﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using com.kmxy.Common;
using com.kmxy.MonitorModel;

namespace AppDemos
{
    class Program
    {
        private static GlobalToolkit tool = GlobalToolkit.GetInstance();
        public delegate bool ControlCtrlDelegate(int CtrlType);
        [DllImport("kernel32.dll")]
        private static extern bool SetConsoleCtrlHandler(ControlCtrlDelegate HandlerRoutine, bool Add);
        private static ControlCtrlDelegate cancelHandler = new ControlCtrlDelegate(HandlerRoutine);


        private static readonly string CurrentPath = AppDomain.CurrentDomain.BaseDirectory;


        public static bool HandlerRoutine(int CtrlType)
        {
            try
            {


                switch (CtrlType)
                {
                    case 0:
                        tool.P("程序关闭...(PressCtrl+C)"); //Ctrl+C关闭  
                        break;
                    case 2:
                        tool.P("程序关闭...(ClickClose)");//按控制台关闭按钮关闭  
                        break;
                }
                tool.Logs(typeof(Program), $"程序关闭，闭关方式：{CtrlType}", "HandlerRoutine()", LogType.Info);
            }
            catch (Exception e)
            {
                tool.Logs(typeof(Program), e, "HandlerRoutine()", LogType.Error);
            }

            Thread.Sleep(3000);
            return false;
        }

        static void Main(string[] args)
        {
            SetConsoleCtrlHandler(cancelHandler, true);

            MonitorConfig config = new MonitorConfig()
            {
                Interval = 15000,
                ModelList = new List<ProcModel>
                {
                    new ProcModel
                    {
                        Args = "AppDemos",
                        Name = "AppDemos1.exe",
                        Path = @"$apps\appa",
                        WaitTime =  5000,
                        WorkPath = @"$apps\appa",
                    },
                    new ProcModel
                    {
                        Args = "AppDemos",
                        Name = "AppDemos2.exe",
                        Path = @"$apps\appb",
                        WaitTime =  5000,
                        WorkPath = @"$apps\appb",
                    }
                }
            };

            var msg = Newtonsoft.Json.JsonConvert.SerializeObject(config);

            var content = File.ReadAllText("config.json");
            if (!string.IsNullOrWhiteSpace(content))
                config = Newtonsoft.Json.JsonConvert.DeserializeObject<MonitorConfig>(content);

            if (config?.ModelList.Count > 0)
            {
                config.ModelList.ForEach(x =>
                {
                    if (x.Path.Substring(0, 1) == "$")
                    {
                        x.Path = $"{CurrentPath}{x.Path.Substring(1, x.Path.Length - 1)}";
                    }
                    if (x.WorkPath.Substring(0, 1) == "$")
                    {
                        x.WorkPath = $"{CurrentPath}{x.WorkPath.Substring(1, x.WorkPath.Length - 1)}";
                    }
                });
            }
            else
            {
                throw new Exception("加载配置文件异常，服务初始化失败！");
            }


            var rnd = new Random(DateTime.Now.Second);
            tool.Logs(typeof(Program), "Appdemo is start!!!", "Main()");
            while (true)
            {
                var n = rnd.Next(20, 60);
                tool.Logs(typeof(Program), $"Sleep {n} second for next!", "Main()");

                Thread.Sleep(n * 1000);
            }
        }
    }
}
